package cn.rdq.iknessplatform.controller;

import cn.rdq.api.po.User;
import cn.rdq.api.vo.LoginUser;
import cn.rdq.common.CommonResult;
import cn.rdq.common.constant.SysCurrentInfo;
import cn.rdq.common.exception.ExceptionStatus;
import cn.rdq.common.util.RedisUtil;
import cn.rdq.iknessplatform.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;


@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisUtil redisUtil;

    @PostMapping("/login")
    public CommonResult login(@RequestBody LoginUser loginUser) {
        User user = userService.loginByUsernameAndPassword(loginUser);
        if (ObjectUtils.isEmpty(user)) {
            return CommonResult.success().failed(ExceptionStatus.PasswordError);
        }
        Map<String, Object> map = new HashMap<>();
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        redisUtil.set(token, user, 1800);
        map.put("user", user);
        map.put("token", token);
        SysCurrentInfo.incrOnline();
        SysCurrentInfo.incrViewsToday();
        return CommonResult.success().success(map);
    }

    @GetMapping("/list")
    public CommonResult list() {
        return CommonResult.successObj(userService.listUser());
    }

    @PostMapping("/register")
    public CommonResult register(@RequestBody User user) {
        Map<String, Object> map = new HashMap<>();
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        redisUtil.set(token, user, 1800);
        map.put("user", userService.register(user));
        map.put("token", token);
        return CommonResult.successObj(map);
    }

    @PostMapping("/update")
    public CommonResult update(@RequestBody User user) {
        userService.updateUser(user);
        return CommonResult.success();
    }

    @GetMapping("/{id}")
    public CommonResult getUserById(@PathVariable Long id) {
        return CommonResult.successObj(userService.getById(id));
    }

    @GetMapping("/tokenUser")
    public CommonResult tokenUser(String token) {
        User user = (User) redisUtil.get(token);
        return CommonResult.successObj(user);
    }
}
